import store from '@/store';
import { computed, ComputedRef } from 'vue';

const baseUrl : ComputedRef<string> = computed(() => store.state.baseUrl);

//http://8.129.110.73:82/api
//http://redpack.gdlzjt.com/api


const config : IHttpConfig = {
	showLoading: true,
	loadingMask: true,
	loadingText: '努力加载中~',
	loadingTime: 800,
	timer: undefined,
}


class Http implements IHttp {
	readonly baseUrl : string;
	public config : IHttpConfig;
	constructor(baseUrl : string, config : IHttpConfig) {
		this.baseUrl = baseUrl;
		this.config = config;
	};
	GET(url : string, data ?: AnyObject, header ?: any) : Promise<requestData | UniNamespace.GeneralCallbackResult> {
		const options : UniNamespace.RequestOptions = {
			method: 'GET',
			url,
			data,
			header
		}
		return this.REQUEST(options)
	};
	POST(url : string, data ?: AnyObject, header ?: any) : Promise<requestData | UniNamespace.GeneralCallbackResult> {

		const options : UniNamespace.RequestOptions = {
			method: 'POST',
			url,
			data,
			header
		}
		return this.REQUEST(options)
	};
	DELETE(url : string, data ?: AnyObject, header ?: any) : Promise<requestData | UniNamespace.GeneralCallbackResult> {
		const options : UniNamespace.RequestOptions = {
			method: 'DELETE',
			url,
			data,
			header
		}
		return this.REQUEST(options)
	};
	PUT(url : string, data ?: AnyObject, header ?: any) : Promise<requestData | UniNamespace.GeneralCallbackResult> {
		const options : UniNamespace.RequestOptions = {
			method: 'PUT',
			url,
			data,
			header
		}
		return this.REQUEST(options)
	};
	REQUEST(options : UniNamespace.RequestOptions) : Promise<requestData | UniNamespace.GeneralCallbackResult> {
		return new Promise((resolve, reject) => {
			const request_options : UniNamespace.RequestOptions = {
				...options,
				success: (res) => {
					if (res.isSuccess) {
						resolve((res.data as requestData))
					} else {
						reject((res.data as requestData))
					}
				},
				fail: (err) => {
					console.log('拦截器fail====>', err);
					reject(err)
				}
			}
			uni.request(request_options)
		})
	}
}




export {
	baseUrl,
	config,
	Http
}